<!--出库管理列表页面-->
<template>
  <div class="app-container">
    <el-form
      ref="form"
      inline
      :model="form"
      class="form-options"
      label-width="100px"
    >
      <!--TODO lihuaibei 查询客户信心-->
      <el-form-item label="客户名称">
        <el-autocomplete
          ref="customerNameRef"
          v-model="form.customerName"
          placeholder="请选择客户名称"
          value-key="name"
          :fetch-suggestions="querySearchBatchNo"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectBatchNo"
          @clear="clickClearcustomerNameRef"
        />
      </el-form-item>
      <!--TODO lihuaibei 查询客户信心-->
      <el-form-item label="出库单号">
        <el-autocomplete
          ref="outNoRef"
          v-model="form.outNo"
          placeholder="请选择出库单号"
          value-key="name"
          :fetch-suggestions="querySearchBatchNo"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectBatchNo"
          @clear="clickClearoutNoRef"
        />
      </el-form-item>
      <!--<el-form-item label="产品类型">-->
      <!--  &lt;!&ndash;fishSpecies 用的是鱼品类型，实际应该是产品类型&ndash;&gt;-->
      <!--  <el-autocomplete-->
      <!--    v-model="form.fishSpecies"-->
      <!--    value-key="name"-->
      <!--    :fetch-suggestions="querySearchPurchaseNo"-->
      <!--    :trigger-on-focus="true"-->
      <!--    clearable-->
      <!--    @select="handleSelectPurchaseNo"-->
      <!--  />-->
      <!--</el-form-item>-->

      <!--<el-form-item label="质检员">-->
      <!--  <el-autocomplete-->
      <!--    v-model="form.qcName"-->
      <!--    value-key="userName"-->
      <!--    :fetch-suggestions="querySysUser"-->
      <!--    :trigger-on-focus="true"-->
      <!--    clearable-->
      <!--    @select="handleSelectSysUser"-->
      <!--  />-->
      <!--</el-form-item>-->

      <!--<el-form-item label="鱼塘">-->
      <!--  <el-autocomplete-->
      <!--    v-model="form.fishpondName"-->
      <!--    value-key="name"-->
      <!--    :fetch-suggestions="querySearchFishpondName"-->
      <!--    :trigger-on-focus="true"-->
      <!--    clearable-->
      <!--    @select="handleSelectFishpondName"/>-->
      <!--</el-form-item>-->

      <el-form-item label="状态">
        <el-select
          v-model="form.status"
          filterable
          clearable
          placeholder="请选择状态"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="出库时间" class="long-content">
        <el-date-picker
          v-model="form.date"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="操作人">
        <el-autocomplete
          ref="operNameRef"
          v-model="form.operName"
          placeholder="请选择操作人"
          value-key="userName"
          :fetch-suggestions="querySysUser"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectOperName"
          @clear="clickClearoperNameRef"
        />
      </el-form-item>

      <div class="btns">
        <el-button
          type="primary"
          v-permission="['out_manage_query']"
          @click="onQuery"
          >查询</el-button
        >
        <el-button
          type="primary"
          v-permission="['out_manage_add']"
          @click="onAdd"
          >新增</el-button
        >
      </div>
    </el-form>

    <!--数据列表-->
    <el-table
      :data="tableData"
      header-cell-class-name="table-header"
      style="width: 100%; margin-top: 20px"
      @row-click="rowClick"
    >
      <el-table-column label="序号" type="index" width="45"> </el-table-column>
      <el-table-column prop="customerName" label="客户名称"> </el-table-column>
      <el-table-column prop="outNo" label="出库单号"> </el-table-column>
      <el-table-column prop="outTime" label="出库完成时间" width="135">
      </el-table-column>
      <!-- <el-table-column prop="fishSpeciesOne" label="产品1">
      </el-table-column>
      <el-table-column prop="outNumOne" label="产品1数量">
      </el-table-column>
      <el-table-column prop="fishSpeciesTwo" label="产品2">
      </el-table-column>
      <el-table-column prop="outNumTwo" label="产品2数量">
      </el-table-column> -->
      <el-table-column prop="outExplain" label="出库说明">
        <template slot-scope="scope">
          <el-tooltip
            class="item"
            effect="dark"
            :content="scope.row.outExplain"
            placement="top"
          >
            <div class="ellipsis-text">{{ scope.row.outExplain }}</div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column prop="operName" label="出库操作人" width="90">
      </el-table-column>
      <el-table-column prop="createTime" label="出库单创建时间" width="135">
      </el-table-column>

      <el-table-column prop="status" label="状态" width="60"> </el-table-column>

      <el-table-column label="操作" width="220px">
        <template slot-scope="scope">
          <el-button
            type="primary"
            v-permission="['out_manage_show']"
            @click="handleOperateClick(scope.row, '查看')"
            >查看
          </el-button>
          <el-button
            type="primary"
            v-permission="['out_manage_edit']"
            v-if="scope.row.status == '未确认'"
            @click="handleOperateClick(scope.row, '修改')"
            >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right; margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-table
      :data="rowList"
      header-cell-class-name="table-header"
      style="width: 100%; margin-top: 40px"
    >
      <el-table-column prop="fishSpecies" label="鱼品种类名称" align="center">
      </el-table-column>
      <el-table-column prop="fishSpeciesId" label="鱼品种类id" align="center">
      </el-table-column>
      <el-table-column prop="fishQuantity" label="鱼出库数量" align="center">
      </el-table-column>
    </el-table>

    <el-dialog
      :title="dialogTitle"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="1300px"
    >
   
      <WarehouseExComponent
        @onSave="onSave"
        :type="warehouseExType"
        @onSubmit="onSubmit"
        :form="dataForm"
        ref="WarehouseExComponent"
      />
      <span slot="footer">
        <!--确认状态是出库完成后（后续可能需要修改为可以部分提交，提交的不能改，但是还能继续扫，防止不能一次性扫完）-->
        <el-button
          type="primary"
          v-if="warehouseExType >= 1"
          @click="saveData()"
          >保存</el-button
        >
        <!--<el-button type="primary" v-if="warehouseExType>=1" @click="submitData()">保存并提交</el-button>-->
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTypes,
  getUserCondition,
  querySearchFishpondName,
} from "@/api/common";
import WarehouseExComponent from "../components/WarehouseExComponent";
import WarehouseReturnComponent from "../components/WarehouseReturnComponent";

import {

  delWarehouseEx,
  getWarehouseExList,
  getWarehouseExNo,

  getBatchNos
} from "@/api/warehouse";

export default {
  name: "WarehouseEx",
  components: {
    WarehouseExComponent,
    WarehouseReturnComponent,
  },
  data() {
    return {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      form: {
        date: "",
        outTimeStart: "",
        outTimeEnd: "",
        outNo: "",
        fishSpecies: "",
        keyword: "",
        warehouseId: "",
        warehouseName: "",
        status: "",
        fishSpeciesList: [],
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      loading: false,
      tableData: [],
      dialogVisible: false,
      dialogTitle: "新增出库",
      returnDialogVisible: false,
      purchaseOptions: [],
      statusOptions: [
        {
          label: "已确认",
          value: 1,
        },
        {
          label: "未确认",
          value: 0,
        },
      ],
      warehouseExType: 2,
      dataForm: {},
      returnDataId: "",
      warehouseOptions: [],
      showSubmit: false,
      sysUsers: [],
      fishpond: [],
      rowList: [],
    };
  },
  created() {
    getUserCondition({}).then((res) => {
      this.sysUsers = res.resultData;
    });

    querySearchFishpondName({}).then((res) => {
      this.fishpond = res.resultData;
    });
    this.onQuery();
  },
  methods: {
    handleSizeChange: function (val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getTableData();
    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.getTableData();
    },
    //获取鱼品类型
    querySearchPurchaseNo: function (queryString, cb) {
      // const r = this.warehouseOptions
      const r = [{ name: "黑鱼" }, { name: "黑鱼鱼片" }, { name: "鲈鱼" }]; //TODO lihuaibei 后台返回，确保系统一致，好修改
      // console.log(JSON.stringify(r)+"********************************");
      var rs = queryString ? r.filter(this.createFilter(queryString)) : r;
      cb(rs);
    },
    handleSelectPurchaseNo(item) {
      this.form.fishSpecies = item.name;
    },

    //获取用户信息
    querySysUser: function (queryString, cb) {
      const r = this.sysUsers;
      // console.log(JSON.stringify(r)+"********************************");
      var rs = queryString
        ? r.filter(this.createFilterUserName(queryString))
        : r;
      cb(rs);
    },
    handleSelectSysUser(item) {
      this.form.qcName = item.userName;
    },

    //实时从后台查询需要等待，要用同步
    querySearchBatchNo: async function (queryString, cb) {
      let r = [];
      await getBatchNos({ name: queryString }).then((res) => {
        r = res.resultData;
      });
      cb(r);
    },
    handleSelectBatchNo(item) {
      this.form.BatchNo = item.value;
    },
    clickClearcustomerNameRef() {
      this.$nextTick(() => {
        if (this.$refs.customerNameRef) {
          this.$refs.customerNameRef.activated = true;
        }
      });
    },
    clickClearoutNoRef() {
      this.$nextTick(() => {
        if (this.$refs.outNoRef) {
          this.$refs.outNoRef.activated = true;
        }
      });
    },
    clickClearoperNameRef() {
      this.$nextTick(() => {
        if (this.$refs.operNameRef) {
          this.$refs.operNameRef.activated = true;
        }
      });
    },
    querySearchFishpondName: function (queryString, cb) {
      const r = this.fishpond;
      var rs = queryString ? r.filter(this.createFilter(queryString)) : r;
      cb(rs);
    },
    handleSelectFishpondName(item) {
      this.form.fishpondName = item.value;
    },

    //模糊建议公共方法
    createFilter(queryString) {
      return (rr) => {
        return rr.name.toLowerCase().indexOf(queryString.toLowerCase()) != -1;
      };
    },
    createFilterUserName(queryString) {
      return (rr) => {
        return (
          rr.userName.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        );
      };
    },
    onQuery() {
      this.currentPage = 1;
      this.getTableData();
      this.rowList = [];
    },
    getTableData() {
      if (this.form.date && this.form.date[0]) {
        this.form.outTimeStart = this.form.date[0];
      } else {
        this.form.outTimeStart = "";
      }
      if (this.form.date && this.form.date[1]) {
        this.form.outTimeEnd = this.form.date[1];
      } else {
        this.form.outTimeEnd = "";
      }
      const param = { page: this.currentPage, rows: this.pageSize };
      Object.assign(param, this.form);
      getWarehouseExList(param).then((res) => {
        this.tableData = res.resultData;
        this.total = res.total;
      });
    },

    //点击获取子表数据
    rowClick(row) {
      if (row?.fishSpeciesList?.length && row?.fishSpeciesList.length > 0) {
        this.rowList = row?.fishSpeciesList;
        console.log(this.rowList, "this.rowList");
      } else {
        this.rowList = [];
      }
    },
    handleOperateClick(row, tag) {
      if (tag == "删除") {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          delWarehouseEx({ id: row.id }).then((res) => {
            this.onQuery();
          });
        });
      } else if (tag == "查看") {
        this.dialogTitle = "查看出库";
        this.queryDetail(row.id, true);
      } else if (tag == "修改") {
        this.dialogTitle = "编辑出库";
        this.queryDetail(row.id, false);
      }
    },
    queryDetail(id, isReadOnly) {
      const param = { page: 1, rows: 1, id: id };
      const a = "";

      const b = new Promise((resolve) => {
        getWarehouseExList(param).then((res) => {
          console.log(res, "getWarehouseExList");
          resolve(res.resultData[0]);
        });
      });

      Promise.all([a, b]).then((res) => {
        console.log(res, "res");
        const data = res[1];
        console.log(data, "data");
        this.dataForm = data;

        this.warehouseExType = isReadOnly ? 0 : 1;
        this.dialogVisible = true;
      });
    },

    handleSelectOperName(item) {
      this.form.operName = item.userName;
    },
    handleSelectPurchaseName(item) {
      this.form.purchaseName = item.value;
    },

    addEquipment() {
      this.$refs["WarehouseExComponent"].addEquipment();
    },
    saveData() {
      this.$refs["WarehouseExComponent"].save(); //子组件的方法
    },
    onSave() {
      this.dialogVisible = false;
      this.onQuery();
    },
    submitData() {
      this.$refs["WarehouseExComponent"].saveAndSubmit();
    },
    onSubmit() {
      this.dialogVisible = false;
      this.onQuery();
    },
    submitReturnData() {
      this.$refs["WarehouseReturnComponent"].saveAndSubmit();
    },
    onSubmitReturn() {
      this.$message({ type: "success", message: "提交成功！" });
      this.returnDialogVisible = false;
      this.onQuery();
    },
    onShowSubmit(e) {
      this.showSubmit = e;
    },

    onAdd() {
      getWarehouseExNo({}).then((res) => {
        this.dataForm = {
          outNo: res.resultData,
          outExplain: "",
          status: 0,
          warehouseId: "",
          outTime: "",
          operName: "",
          operId: "",
          operTime: "",
          targetLocation: "",
          busOutDetailsList: [],
          fishSpeciesList: [],
          fishQuantity: 0,
          fishSpeciesId: "",
          fishSpeciesId: "",
        };
        this.dialogTitle = "新增出库";
        this.warehouseExType = 2;
        this.dialogVisible = true;
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
.ellipsis-text {
  display: inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%; /* 根据实际情况调整宽度 */
}
</style>
